package com.xxxy.hyc.xyxmp.utils;

import com.xxxy.hyc.xyxmp.bean.CartItem;
import com.xxxy.hyc.xyxmp.bean.Goods;

import java.util.ArrayList;
import java.util.List;

public class CartManager {
    private static CartManager instance;
    private List<CartItem> cartItems;

    private CartManager() {
        cartItems = new ArrayList<>();
    }

    public static synchronized CartManager getInstance() {
        if (instance == null) {
            instance = new CartManager();
        }
        return instance;
    }

    public void addToCart(Goods goods, int quantity) {
        // 检查购物车中是否已有该商品
        for (CartItem item : cartItems) {
            if (item.getGoods().getId() == goods.getId()) {
                item.setQuantity(item.getQuantity() + quantity);
                return;
            }
        }
        // 如果没有该商品，则添加新项目
        cartItems.add(new CartItem(goods, quantity));
    }

    public List<CartItem> getCartItems() {
        return cartItems;
    }

    public void removeCartItem(CartItem item) {
        cartItems.remove(item);
    }

    public void clearCart() {
        cartItems.clear();
    }

    public int getCartItemCount() {
        int count = 0;
        for (CartItem item : cartItems) {
            count += item.getQuantity();
        }
        return count;
    }

    public double getTotalPrice() {
        double total = 0;
        for (CartItem item : cartItems) {
            total += item.getSubtotal();
        }
        return total;
    }
}